<template>
    <view class="wrap">
        <u-form :model="crmFormFields" :rules="crmRules" ref="crmForm" :errorType="['message']">
            <u-form-item label-position="top" :prop="item.data.fieldName" :required="item.data.isNull == 1" v-for="(item, index) in crmForm.crmFields"
                :key="index" :label="item.data.name">
                <!-- 输入框组件 -->
                <component is="XhInput" v-if="item.data.formType == 'text' || item.data.formType == 'number' || item.data.formType == 'floatnumber' || item.data.formType == 'mobile'  || item.data.formType == 'email'"
                    :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation"
                    @value-change="fieldValueChange">
                </component>
                <!-- 文本域组件 -->
                <component is="XhTextarea" v-if="item.data.formType == 'textarea'" :index="index" :item="item" :value="item.value"
                    :disabled="item.disabled" :relation="item.relation" @value-change="fieldValueChange">
                </component>
                <!-- 单选组件 -->
                <component is="XhSelect" v-if="item.data.formType == 'select'" :index="index" :item="item" :value="item.value"
                    :disabled="item.disabled" :relation="item.relation" @value-change="fieldValueChange">
                </component>
                <!-- 时间选择组件 -->
                <component is="XhDateTime" v-if="item.data.formType == 'datetime' || item.data.formType == 'date'"
                    :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation"
                    @value-change="fieldValueChange">
                </component>
                <!-- 关联表 -->
                <component is="XhRelativeTable" v-if="item.data.formType == 'contacts' || item.data.formType == 'customer' || item.data.formType == 'contract' || item.data.formType == 'business'"
                    :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation"
                    :radio="item.radio" @value-change="fieldValueChange">
                </component>
            </u-form-item>
        </u-form>
        <view class="xh-buttons" v-show="!vuex_keyboardStatus">
            <u-button class="xh-button-item" type="primary" @click="saveField(false)">保存</u-button>
        </view>
    </view>
</template>

<script>
    import XhInput from '@/pages/customerManagement/common/components/CreateCom/XhInput';
    import XhSelect from '@/pages/customerManagement/common/components/CreateCom/XhSelect';
    import XhDateTime from '@/pages/customerManagement/common/components/CreateCom/XhDateTime';
    import XhRelativeTable from '@/pages/customerManagement/common/components/CreateCom/XhRelativeTable';
    import XhTextarea from '@/pages/customerManagement/common/components/CreateCom/XhTextarea';
    import crmTypeModel from '@/pages/customerManagement/model/crmTypeModel.js';
    import {
        queryFollowRecordContentFieldsAPI,
        crmSettingRecordListAPI
    } from '@/api/customer/common.js';
    import {
        crmCustomerRecordSave,
        crmCustomerLastRecord
    } from "@/api/customer/customer.js";
    export default {
        data() {
            return {
                params: null,
                crmForm: {
                    crmFields: []
                },
                crmFormFields: {},
                crmType: '',
                crmRules: {},
                recordContentFields: [],
            };
        },
        components: {
            XhInput,
            XhSelect,
            XhDateTime,
            XhRelativeTable,
            XhTextarea
        },
        onLoad(option) {
            //调试结束后启用该代码
            this.params = option.params ? JSON.parse(decodeURIComponent(option.params)) : {};
            this.crmType = this.params.crmType;
            this.getFields();
        },
        watch: {

        },

        computed: {

        },

        onShow() {
            if (uni.getStorageSync("refreshData")) {
                this.getFields();
            }
        },

        methods: {
            // 更改值
            fieldValueChange(data) {
                let item = this.crmForm.crmFields[data.index]
                item.value = data.value;
                //用于校验
                if (data.value && data.value.length) {
                    this.crmFormFields[data.fieldName] = "TRUE";
                } else {
                    this.crmFormFields[data.fieldName] = ''
                }
                if (item.data.formType == 'customer') {
                    let field = this.crmForm.crmFields.find(item => item.data.formType == 'contacts');
                    if (data.value && data.value.length) {
                        field['relation'].customerId = data.value[0].customerId;
                    } else {
                        field['relation'].customerId = null;
                    }
                    this.handleLaseRecord(data.value[0]);
                    field.value = [];
                }
            },

            // 获取字段
            getFields() {
                let self = this;
                queryFollowRecordContentFieldsAPI().then(res => {
                    self.recordContentFields = res.data.list;
                    self.handleFollowRecordFields()
                })
            },

            // 通过选择客户获取最近一次跟进记录，并赋值
            handleLaseRecord(value) {
                let self = this;
                if (value) {
                    let params = {
                        typesId: value.customerId
                    }
                    crmCustomerLastRecord(params).then(res => {
                        let data = res.data ? res.data : {};
                        self.recordContentFields.map(content => {
                            if (content.nextValueTwo == 'AUTO') {
                                let field = self.crmForm.crmFields.find(item => item.data.fieldName ==
                                    content.name);
                                if (!(field.value && field.value.length)) {
                                    field.value = data[content.name] ? data[content.name] : '';
                                } else {
                                    field.value = '';
                                }
                            }
                        })
                        let field = this.crmForm.crmFields.find(item => item.data.fieldName == 'equipmentNum');
                        field.value = data.equipmentNum
                    })
                } else {
                    self.recordContentFields.map(content => {
                        if (content.nextValueTwo == 'AUTO') {
                            let field = self.crmForm.crmFields.find(item => item.data.fieldName == content.name);
                            field.value = '';
                        }
                    })
                    let field = this.crmForm.crmFields.find(item => item.data.fieldName == 'equipmentNum');
                    field.value = ""
                }

            },

            // 跟进记录字段整理
            handleFollowRecordFields() {
                let self = this;
                let contents = self.recordContentFields;
                crmSettingRecordListAPI().then(res => {
                    let fields = [{
                        "formType": "customer",
                        "isNull": 1,
                        "isDisabled": 0,
                        "isUnique": 0,
                        "inputTips": null,
                        "fieldName": "typesId",
                        "name": "客户名称",
                        "value": ""
                    }, {
                        "formType": "contacts",
                        "isNull": 1,
                        "isDisabled": 0,
                        "isUnique": 0,
                        "inputTips": null,
                        "fieldName": "contactsIds",
                        "name": "客户联系人",
                        "value": ""
                    }, {
                        "formType": "select",
                        "isNull": 1,
                        "isDisabled": 0,
                        "isUnique": 0,
                        "inputTips": null,
                        "fieldName": "category",
                        "name": "跟进方式",
                        "setting": res.data,
                        "value": ""
                    }]
                    let arr = [];
                    contents.map(item => {
                        let field = {
                            "formType": "textarea",
                            "isNull": 0,
                            "isDisabled": 0,
                            "isUnique": 0,
                            "inputTips": null,
                            "fieldName": "",
                            "name": "",
                            "value": ""
                        }
                        if (item.nextValueOne == 'TRUE') {
                            field.isNull = 1;
                        }
                        field.fieldName = item.name;
                        field.name = item.value;
                        arr.push(field);
                    })
                    fields = fields.concat(arr);
                    let field2 = [
                        // {
                        //     "formType": "file",
                        //     "isNull": 0,
                        //     "isDisabled": 0,
                        //     "isUnique": 0,
                        //     "inputTips": null,
                        //     "fieldName": "batchId",
                        //     "name": "附件",
                        //     "value": ""
                        // },
                        {
                            "formType": "datetime",
                            "isNull": 1,
                            "isDisabled": 0,
                            "isUnique": 0,
                            "inputTips": null,
                            "fieldName": "nextTime",
                            "name": "下次联系时间",
                            "value": ""
                        },
                        {
                            "formType": "number",
                            "isNull": 1,
                            "isDisabled": 0,
                            "isUnique": 0,
                            "inputTips": null,
                            "fieldName": "equipmentNum",
                            "name": "设备台数",
                            "value": ""
                        }
                    ]
                    fields = fields.concat(field2);
                    self.getCrmRulesAndModel(fields)
                })

            },

            getCrmRulesAndModel(list) {
                let self = this;
                let fields = [];
                let formFields = {};
                let crmRules = {};
                for (let index = 0; index < list.length; index++) {
                    const item = list[index]
                    /**
                     * 规则数据
                     */
                    crmRules[item.fieldName] = this.getItemRulesArrayFromItem(item)
                    /**
                     * 表单数据
                     */
                    let params = {};
                    params['key'] = item.fieldName;
                    params['data'] = item;
                    params['disabled'] = item.isDisabled == 1;
                    params['value'] = item.value;
                    params['relation'] = {}; // 自定义参数
                    if (item.formType == 'datetime') {
                        // params['relation']['dateType'] = 'datetime-all';
                    } else if (item.formType == 'customer') {
                        //关联数据类型actionType
                        if (item.value.length) {
                            params['value'] = item.value;
                        } else {
                            params['value'] = []
                        }
                        params['relation']['actionType'] = 'customer';
                    } else if (item.formType == 'contacts') {
                        //关联数据类型actionType
                        if (item.value.length) {
                            params['value'] = item.value;
                        } else {
                            params['value'] = []
                        }
                        params['radio'] = true;
                        // parentType 指是父类型，即与父类有上下级数据关联
                        params['relation']['parentType'] = 'customer';
                        params['relation']['actionType'] = 'contacts';
                    }
                    fields.push(params);
                    //将表单中涉及的字段放到crmFormFields，用户后续form的校验
                    formFields[item.fieldName] = '';
                }
                this.crmForm.crmFields = fields;
                this.crmFormFields = formFields;
                this.crmRules = crmRules;
                self.$nextTick(function() {
                    self.$refs.crmForm.setRules(self.crmRules);
                })
            },

            getItemRulesArrayFromItem(item) {
                var tempList = []
                // 验证必填
                if (item.isNull == 1) {
                    tempList.push({
                        required: true,
                        message: item.name + '不能为空',
                        trigger: ['blur', 'change'],
                        type: 'string'
                    })
                }

                if (item.formType == 'mobile') {
                    var validateCRMMobile = (rule, value, callback) => {
                        if (!value || value == '' || this.$u.test.mobile(value)) {
                            callback()
                        } else {
                            callback(new Error('手机格式有误'))
                        }
                    }
                    tempList.push({
                        validator: validateCRMMobile,
                        item: item,
                        trigger: ['blur']
                    })
                } else if (item.formType == 'email') {
                    var validateCRMEmail = (rule, value, callback) => {
                        if (!value || value == '' || this.$u.test.email(value)) {
                            callback()
                        } else {
                            callback(new Error('邮箱格式有误'))
                        }
                    }
                    tempList.push({
                        validator: validateCRMEmail,
                        item: item,
                        trigger: ['blur']
                    })
                }
                return tempList
            },

            // ==================== 保存数据 ===================
            // 保存草稿
            saveDraftField() {
                this.saveField(false, true)
            },
            // 保存数据
            saveField(saveAndCreate, isDraft = false) {
                // this.saveAndCreate = saveAndCreate
                this.$refs.crmForm.validate(valid => {
                    if (valid) {
                        var params = this.getSubmiteParams(this.crmForm.crmFields)
                        this.submiteParams(params)
                    } else {
                        this.$u.toast("存在字段填写不规范！");
                        return false
                    }
                })
            },
            /** 上传 */
            submiteParams(params) {
                crmCustomerRecordSave(params)
                    .then(res => {
                        uni.navigateBack();
                        uni.setStorageSync("refreshData", true);
                    })
                    .catch(() => {
                        this.loading = false
                    })
            },

            /** 拼接上传传输 */
            getSubmiteParams(array) {
                var params = {}
                params['isEvent'] = 0;
                for (let index = 0; index < array.length; index++) {
                    let item = array[index];
                    if (item.key == 'typesId') {
                        params[item.key] = item.value[0][item.relation.actionType + 'Id'];
                    } else if (item.key == 'contactsIds') {
                        let str = "";
                        let count = 0;
                        item.value.map(data => {
                            count++;
                            if (count < item.value.length) {
                                str += data[item.relation.actionType + 'Id'] + ",";
                            } else {
                                str += data[item.relation.actionType + 'Id']
                            }
                        })
                        params[item.key] = str;
                    } else {
                        params[item.key] = item.value;
                    }
                }
                let fields = this.recordContentFields;
                let content = "";
                fields.map(field => {
                    content += '<em>' + field.value + '</em>' + "\r\n";
                    content += params[field.name] + "\r\n";
                })
                params.content = content;
                return params
            },

        }
    };
</script>

<style scoped lang="scss">
    .wrap {
        padding: 0 30rpx;
        padding-bottom: 90rpx;
        background: #fff;
    }

    .xh-buttons {
        width: 100%;
        position: fixed;
        bottom: 0;
        left: 0;
        display: flex;
        flex-direction: row;
        z-index: 10;

        .xh-button-item {
            width: 100%;
            border-radius: 0;
            border: none;
        }
    }

    .u-form-item {
        padding: 20rpx 0 0 0;
        line-height: 1;

        /deep/ .u-form-item__message {
            margin: 0;
            padding-bottom: 10rpx;
        }

        /deep/ .u-form-item--left {
            margin: 0 !important;
        }
    }
</style>
